import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author Jiange
 * @create 2021-05-13-21:03
 */

class MyTask extends RecursiveTask<Integer>{

    private static final Integer ADJUST = 10;
    private int begin;
    private int end;
    private int result;

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if((end - begin)<=ADJUST){
            for (int i = begin; i < end; i++) {
                result = result + i;
            }
        }else {
            int middle = (end + begin)/2;
            MyTask myTask = new MyTask(begin,middle);
            MyTask myTask1 = new MyTask(middle + 1, end);
            myTask.fork();
            myTask1.fork();
            result = myTask.join() + myTask1.join();
        }
        return result;
    }
}

public class ForkJoinTaskDemo {
    public static void main(String[] args) {
        MyTask myTask = new MyTask(0, 100);

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> submit = forkJoinPool.submit(myTask);

        try {
            System.out.println(submit.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}